import React, {useRef, useState} from "react";
import {defaultPagination, paginationTool} from "@/utils/util";
import {useMount, useRequest} from "ahooks";
import ProTable from "@ant-design/pro-table";
import {getResult} from "@/services/ant-design-pro/attribute";
import {Button, message} from "antd";
import {editAdvertising, findAdvertisingByPageList} from "@/services/ant-design-pro/advertising";
import {BetaSchemaForm, ProFormInstance} from "@ant-design/pro-form";
import {PlusOutlined} from "@ant-design/icons";
import MyUpload from "../../../components/MyUpload";
import {findByDataCategoryListPageSelect} from "../../../services/ant-design-pro/menu";

const getAttr = async (key: string) => {
  let result = await getResult ( key, 1 );
  return result
}
const request1 = async () => {
  return new Promise<API.SelectItem[]> ( (resolve, reject) => {
    findByDataCategoryListPageSelect ()
      .then ( (res) => {
        let selectItems = res.data;
        selectItems.unshift ( {label: '下一单', value: ""} );
        resolve ( selectItems );
      } )
      .catch ( (e) => {
      } );
  } );
};

const columns = [{
  title: "编号",
  key: "id",
  dataIndex: "id",
  search: false,
}, {
  title: "图片",
  key: "image",
  dataIndex: "image",
  valueType: "image",
  fieldProps: {
    width: 200,
    height: 100
  }


}, {
  title: "标题",
  key: "title",
  dataIndex: "title"
}, {
  title: "备注",
  key: "remark",
  dataIndex: "remark"
}, {
  title: "广告类型",
  key: "type",
  dataIndex: "type",
  valueType: "select",
  valueEnum: await getResult ( 'advertisingManagementType', 0 )
},  {
  title: '地址',
  dataIndex: 'path',
  key: 'path',
  width: 'sm',
  valueType: "select",
  request: request1
}, {
  title: "APPID",
  key: "appid",
  dataIndex: "appid"
}, {
  title: "状态",
  key: "state",
  dataIndex: "state",
  valueType: "select",
  valueEnum: await getResult ( 'sys_global_state', 0 )
}
  , {
    title: "订单时间",
    key: "create_date",
    dataIndex: "create_date",
    valueType: 'dateTime',
    search: false
  }]


const Page: React.FC = () => {
  const [params, setParams] = useState<any> ();
  const formRef = useRef<ProFormInstance> ();
  const [editDialg, setEditDialg] = React.useState ( false );
//  const [columns, setColumns] = useState ( column );
  // const [columnDialogs, setColumnDialogs] = useState ( columnDialog );
  const [menuInfo, setMenuInfo] = useState<API.MenuInfo> ();

  function editDialogInfo(row, index) {

    formRef?.current?.setFieldsValue ( row );
    setEditDialg ( true );
  }

  function hideEditDialg() {

    formRef.current?.resetFields ();

  }

  function openEditDialg() {

    formRef.current?.resetFields ();
    setEditDialg ( true );
  }

  //findByPageOrderList
  const [pagination, setPagination] = useState<API.Pagination> ( defaultPagination () );

  const {
    run: fetchByPageList,
    refresh,
    data: dataList,
    loading,
  } = useRequest ( findAdvertisingByPageList, {
    debounceWait: 100,
    manual: true,
  } );


  useMount ( () => {
    columns[14] = {
      title: '操作',
      key: 'option',
      valueType: 'option',
      render: (_: any, row: { id: number | undefined; isPay: number | undefined; paymentStatus: number | undefined; }, index: any, action: any) => [
        <Button type="primary"
                onClick={(a) => {
                  console.log ( row );

                  editDialogInfo ( row, index );
                }}>编辑</Button>
      ],
    }
    //   const p = useLocation();
    // console.log ( "onDataSourceChange", query )

    fetchByPageList ( params );
  } );

  const columnDialogs = [{
    title: "编号",
    key: "id",
    dataIndex: "id",
    search: false,
    formItemProps: {
      hidden: true
    }
  }, {
    title: "编号",
    key: "imageId",
    dataIndex: "imageId",
    search: false,
    formItemProps: {
      hidden: true
    }
  }, {
    title: "基本信息", valueType: "group", columns: [{
      title: "图片",
      key: "image",
      dataIndex: "image",
      valueType: "image",
      fieldProps: {
        width: 200,
        height: 100
      },
      width: 'md', renderFormItem: (item: any, f: any, form: any) => {
        const image = form.getFieldValue ( 'image' );
        const id = form.getFieldValue ( 'id' );
        return (<> <MyUpload
            type={4}
            url={image}
            id={id}
            onChange={(event) => {
console.log("MyUpload",event)
              formRef.current?.setFieldsValue ( {imageId: event} );
            }}
          ></MyUpload></>
        )

      }
    }, {
      title: "标题",
      key: "title",
      dataIndex: "title",
      width: 'md'
    }, {
      title: "广告类型",
      key: "type",
      dataIndex: "type",
      valueType: "select",
      request: async () => {
        return await getResult ( 'advertisingManagementType', 1 );
      },
      width: 'md'
    }, {
      title: "目标类型",
      key: "target_type",
      dataIndex: "type",
      valueType: "select",

      request: async () => {
        return await getResult ( 'advertisingTargetType', 1 );
      },
      width: 'md'
    }, {
      title: '地址',
      dataIndex: 'path',
      key: 'path',
      width: 'sm',
      valueType: "select",
      request: request1
    }, {
      title: "APPID",
      key: "appid",
      dataIndex: "appid",
      width: 'md'
    }, {
      title: "备注",
      key: "remark",
      dataIndex: "remark",
      valueType: "textarea",
      width: 'md'
    }]
  }]

  return (<>
    <BetaSchemaForm<API.MenuInfo>
      formRef={formRef}
      initialValues={menuInfo}
      onCancel={() => setEditDialg ( false )}
      onVisibleChange={setEditDialg}
      title="菜单管理"
      visible={editDialg}
      layoutType="ModalForm"
      columns={columnDialogs}
      onFinish={async (values) => {
        // values.id = menuInfo.id;
        console.log ( values );
        return new Promise<Boolean> ( (resolve, reject) => {
          editAdvertising ( values )
            .then ( () => {
              message.success ( '操作成功' );
              setEditDialg ( false );
              refresh ();
              resolve ( true );
            } )
            .catch ( () => {
              message.success ( '操作失败' );
              reject ( false );
            } );
        } );
      }}
    />
    <ProTable

      search={false}
      dataSource={dataList?.data?.list}
      loading={loading}
      pagination={paginationTool ( pagination, dataList?.data?.total, (data1: API.Pagination) => {
        setPagination ( data1 );

        fetchByPageList ( {...data1, ...params} );
      } )}
      search={{
        defaultCollapsed: false,
        labelWidth: 'auto',
      }}
      onSubmit={(params) => {
        // fetchByPageList ( params );
        console.log ( 'onSubmit', params );
        setParams ( {...params} )
        fetchByPageList ( params );
      }}
      cardBordered={true}
      columns={columns}
      toolBarRender={() => [
        <Button
          onClick={() => {
            formRef.current?.resetFields ();
            openEditDialg ();
          }}
          key="button"
          icon={<PlusOutlined/>}
          type="primary"
        >
          新建
        </Button>,
      ]}
    ></ProTable></>)
}

export default Page;
